import axios, { type AxiosRequestConfig } from "axios";
import useStore from "@/stores";
import { ElMessage } from "element-plus";
import router from "@/router";
const axiosConfig = {
  baseURL: "/api",
  withCredentials: false,
  timeout: 60000,
  headers: {},
};
const request = axios.create(axiosConfig);

/* 设置请求拦截器 */
request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (config.headers === undefined) {
      config.headers = {};
    }
    const { user } = useStore();
    const token = user.getToken();
    if (token) {
      config.headers["token"] = `${token}`;
    }
    return config;
  },
  (err: any) => {
    return Promise.reject(err);
  }
);

//设置响应拦截器
request.interceptors.response.use(
  (response: any) => {
    if (response.request.responseType === "blob") {
      return response.data;
    } else if (response.data) {
      if (response.data.code === 401) {
        localStorage.clear();
        router.push("/login");
      } else if (response.data.code !== 200) {
        ElMessage.error(response.data.message);
        return Promise.reject(response.data);
      }
    }
    return response.data;
  },
  (err: any) => {
    return Promise.reject(err);
  }
);

export default request;
